<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>服务器列表</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
{% csrf_token %}
<table border="1">
    <thead>
        <tr>
            <th>全选<input type="checkbox" id="selectALL"></th>
            <th>主机名</th>
            <th>IP地址</th>
            <th>操作系统</th>
            <th>硬件配置</th>
        </tr>
    </thead>
    <tbody id="tb">
        <tr>
            <td>1<input type="checkbox" value="1"></td>
            <td>test1</td>
            <td>192.168.31.10</td>
            <td>centos7</td>
            <td>8c16g</td>
        </tr>
        <tr>
            <td>2<input type="checkbox" value="2"></td>
            <td>test2</td>
            <td>192.168.31.11</td>
            <td>centos7</td>
            <td>8c16g</td>
        </tr>
        <tr>
            <td>3<input type="checkbox" value="3"></td>
            <td>prod1</td>
            <td>10.0.0.10</td>
            <td>centos7</td>
            <td>4c8g</td>
        </tr>
        <tr>
            <td>4<input type="checkbox" value="4"></td>
            <td>prod2</td>
            <td>10.0.0.11</td>
            <td>centos7</td>
            <td>4c8g</td>
        </tr>
    </tbody>
</table>
<button type="button" id="btn">提交删除</button>
<script>
    // 全选和取消全选
    $("#selectALL").click(function(){
        var all_num = $("#tb input").length;
        var select_num = $("#tb input:checked").length;
        if(all_num == select_num) {
            $("#tb input").prop("checked", false)  // 设置未选中，prop支持布尔值，attr不支持布尔值
        } else {
            $("#tb input").prop("checked", true)  // 设置未选中
        }
    });
    // 删除选择的input id
     $("#btn").click(function(){
        var check = $("#tb input[type=checkbox]:checked");
        var ids = new Array();  // 定义一个数组
        for(let i=0;i<check.length;i++) {  // 解决数组里出现undefined元素
        {#for(i in check){#}
            // ids.push(check[i].value)
            ids[i] = check[i].value
        }
        var csrf_token = $("[name='csrfmiddlewaretoken']").val();
        var data = {'ids': ids, 'csrfmiddlewaretoken': csrf_token};
        console.log(ids);
        // 提交数据
        $.ajax({
            type: "POST",
            url: "/server_table/",
            data: data,
            success: function(result){
                if( result.code == '0'){
                    console.log(result.msg);    // console.log打印
                } else if (result.code == '1') {
                    alert(result.msg)
                }
            },
            error: function () {
                alert("请求服务器接口失败！")
            }
        })
    });
</script>
</body>
</html>